<template>
  <div class="bc-filter-bar bc-filter-bar-adapter">
    <div class="body adaptive-item-wrapper">
      <slot></slot>
      <div class="adaptive-item footer">
        <slot name="footer">
          <div class="footer-wrapper">
            <e-button
              type="primary"
              @click="emitEvent('toSearch')">{{ searchText }}</e-button>
            <e-button
              style="margin-left: 10px"
              @click="emitEvent('toReset')">{{ resetText }}</e-button>
            <e-button
              style="margin-left: 5px"
              v-if="isShowExpand"
              type="drop"
              @click="expandBody"
              :class="isExpand ? 'icon-btn rotate-icon' : 'icon-btn'">
              {{ !isExpand ? '展开' : '收起' }}
              <e-icon size="10" type="arrow-down"> </e-icon>
            </e-button>
          </div>
        </slot>
      </div>
    </div>
  </div>
</template>
<script>
import elementResizeDetectorMaker from 'element-resize-detector'

export default {
  name: 'AdapterSearchPane',
  props: {
    searchText: {
      type: String,
      default: '查询'
    },
    resetText: {
      type: String,
      default: '重置'
    },
    minWidth: {
      type: Number,
      default: 300
    },
    maxColumn: {
      type: Number,
      default: 5
    },
    showExpand: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      isExpand: false,
      perWidth: 4,
      isShowExpand: this.showExpand
    }
  },
  methods: {
    setShowFlag (items) {
      let flag = false
      items.forEach(item => !flag ? flag = item.style.display === 'none' : null)
      this.isShowExpand = this.isExpand ? true : (this.showExpand && flag)
    },
    handleResize () {
      const items = this.$el.querySelectorAll('.adaptive')
      const offsetWidth = this.$el.querySelector('.adaptive-item-wrapper').offsetWidth
      const column = Math.floor(offsetWidth / this.minWidth)
      this.perWidth = column > this.maxColumn ? this.maxColumn : column < 2 ? 1 : column
      items.forEach((item, index) => {
        item.style.minWidth = `${this.minWidth}px`
        item.style.width = `${100 / this.perWidth}%`
        if (!this.isExpand && index > this.perWidth - 2 && index !== items.length - 1 && index !== 0) {
          item.style.display = 'none'
        } else {
          item.style.display = 'flex'
        }
      })
      this.setShowFlag(items)
    },
    expandBody () {
      this.isExpand = !this.isExpand
      this.handleResize()
    },
    emitEvent (eventName) {
      this.$emit(eventName)
    }
  },
  mounted () {
    this.handleResize()
    this.observer = elementResizeDetectorMaker()
    this.observer.listenTo(this.$el, this.handleResize)
  },
  beforeUnmount () {
    this.observer.removeListener(this.$el, this.handleResize)
  }
}
</script>
